package sign

import (
	"encoding/json"
)

var signList = make(map[string]Sign)

type Sign interface {
	// 生成签名 签名内容 私钥
	Sign([]byte, []byte) (string, error)
	// 验签数据 签名内容 公钥 签名
	Verify([]byte, []byte, string) error
}

func RegisterSignObject(name string, value Sign) {
	if value == nil {
		panic("sign: can not register empty object")
	}
	if _, dup := signList[name]; dup {
		panic("sign: dumplicate key " + name)
	}
	signList[name] = value
}

func GetSignObject(name string) Sign {
	if v, ok := signList[name]; ok {
		return v
	}
	return nil
}

//将结构体转为用于签名的有序json字符串
func Object2OrderJson(object interface{}) ([]byte, error) {
	ab, err := json.Marshal(object)
	if err != nil {
		return nil, err
	}
	return Json2OrderJson(ab)
}

func Json2OrderJson(content []byte) ([]byte, error) {
	var mobj map[string]interface{}
	err := json.Unmarshal(content, &mobj)
	if err != nil {
		return nil, err
	}

	if _, ok := mobj["sign"]; ok {
		delete(mobj, "sign")
		// return nil, fmt.Errorf("sign: sign parameter not exist")
	}
	// delete(mobj, "sign")
	return json.Marshal(mobj)
}
